const http = require("http")
const fs = require("fs")
const path = require("path")

http.createServer((req, res) => {
    var urlObj = new URL(req.url, "http://localhost:8081/")
    var pathName = urlObj.pathname;
    if (req.url == '/') {
        var fileContent = fs.readFileSync("./index.html")
        res.writeHead(200, { "Content-Type": "text/html;charset=utf8" })
        res.write(fileContent);
        res.end()
    } else if (pathName == '/upload') {
        var str = ''
        req.setEncoding("binary")
        req.on("data", (chunk) => {
            str += chunk
        })
        req.on("end", () => {
            var arr = str.split("\r\n");
            var imgArr = arr.slice(4, arr.length - 2);//截取图片的字符串数据
            var imgStr = imgArr.join("\r\n");//还原回字符串
            var buf = Buffer.from(imgStr, "binary")//获取图片的buffer数据
            var imgName = arr.slice(1, 2)
            var nameStr = imgName.toString("utf8")
            var nameArr = nameStr.split(";")
            var name = nameArr[2]
            var imgName = name.slice(11, name.length - 1)
            fs.writeFileSync(path.join(__dirname, "/upload/" + imgName), buf, { "encoding": "binary" })
        })
        res.end('success')
    } else if (pathName == '/list') {
        var fileContent = fs.readFileSync("./list.html")
        res.writeHead(200, { "Content-Type": "text/html;charset=utf8" })
        res.write(fileContent)
        res.end()
    }else if(pathName=='/getlist'){
        var dirPath = path.join(__dirname, "/upload");
        var files = fs.readdirSync(dirPath);
        res.writeHead(200, { "Content-Type": "text/html;charset=utf8" })
        res.write(JSON.stringify(files))
        res.end()
    }else if (pathName.indexOf('/img/') ==0 ) {
        var imgPath=path.join(__dirname,'/upload/'+pathName.slice(5))
        var imgBuffer=fs.readFileSync(imgPath)
        res.writeHead(200, { "Content-Type": "text/plain" })
        res.write(imgBuffer)
        res.end()
    }


}).listen(8081)